
package com.et114.modules.org.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.et114.components.acegi.Constants;
import com.et114.components.acegi.cache.AcegiCacheManager;
import com.et114.components.ectable.EXTableUtils;
import com.et114.components.ectable.EctableConverts;
import com.et114.components.ectable.EctableDic;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.exception.CheckException;
//import com.et114.core.utility.PropertyUtils;
import com.et114.core.utility.FileUploadUtil;
import com.et114.core.utility.GetterUtil;
import com.et114.core.utility.NumberUtils;
import com.et114.core.utility.StringPool;
import com.et114.core.utility.ThreadSynchronizer;
import com.et114.modules.org.form.EmpForm;
import com.et114.modules.org.message.FuncMessageManager;
import com.et114.modules.org.message.OrgMessageManager;
import com.et114.modules.org.services.GroupManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.services.RoleManager;
import com.et114.modules.org.services.UserManager;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.utility.tree.OrgGroupTree;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.org.vo.UserEmplyVo;
import com.et114.modules.org.vo.UserVo;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;


//@author zhouxiaoyun , guanhw
public class EmpAction extends BaseDispatchAction {
	private static final String   EMP_JOBSTATE = "jobstate" ; 
	private static final String   EMP_SEX = "sex" ; 
	private static final String   SESSION_ROLES = "selectRoles" ;
	private static final String   SESSION_TITLES = "selectTitles" ;

    public ActionForward listEmp( ActionMapping mapping , ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception { 
        EmpForm empForm = (EmpForm) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ;         
        GroupVo groupVo = new GroupVo();
        PropertyUtils.copyProperties( groupVo , empForm );
        //set convert
        EctableConverts  ec = groupVo.getEconverts ( ) ; 
        ec.setProConvert ( "LOGINNAME" , "c.LOGINNAME" ) ;
        ec.setProConvert ( "TITLENAME" , "b.TITLENAME" ) ;
        ec.setProConvert ( "EMPNAME" , "a.EMPNAME" ) ;
        ec.setProConvert ( "JOBSTATE" , "a.JOBSTATE" ) ;
        
        EctableDic edic = new EctableDic() ; 
        edic.setProName ( "a.JOBSTATE" ) ;
        List ops = DictionaryCache.getInstance ( ).listBizOptions( EMP_JOBSTATE ) ;
        for ( java.util.Iterator iter = ops.iterator ( ) ; iter.hasNext ( ) ;  ) {
        	BizOption bizOp = ( BizOption ) iter.next ( ) ;
        	edic.setDicKey ( bizOp.getOptionName ( ) , bizOp.getOptionValue ( ) ) ;
        }
        ec.setDic ( edic ) ; 
        
        
		EXTableUtils.initLimitPage(  groupVo , request ) ;
        Long rl = getGroupManager ( ).countEmpWithTitles( groupVo ) ; 
        groupVo.setTotalRows ( rl.intValue ( ) ) ; 
		EXTableUtils.setLimitRowAttributes(  groupVo , request ) ;
		List empList = getGroupManager ( ).queryEmpWithTitleList ( groupVo );
		for ( java.util.Iterator iter = empList.iterator ( ) ; iter.hasNext ( ) ; ) {
			Map uev = ( Map )  iter.next ( ) ;
			if ( uev.get ( EMP_JOBSTATE.toUpperCase ( ) ) != null ) {
				String jobState = DictionaryCache.getInstance ( ).getBizOptionName ( EMP_JOBSTATE , uev.get ( EMP_JOBSTATE.toUpperCase ( ) ).toString ( ) ) ;
				uev.put ( EMP_JOBSTATE.toUpperCase ( ) , jobState )  ;
			}
		}
        empForm.setEmpList( empList );
        
        List options = DictionaryCache.getInstance ( ).listBizOptions( EMP_JOBSTATE ) ;
        request.setAttribute ( "jobstates" , options ) ;
        if ( empForm.getEmpName ( ) != null ) request.setAttribute ( "empName" , empForm.getEmpName ( ) ) ;
        if ( empForm.getLoginName ( ) != null ) request.setAttribute ( "loginName" , empForm.getLoginName ( ) ) ;
        if ( empForm.getTitleName ( ) != null ) request.setAttribute ( "titleName" , empForm.getTitleName ( ) ) ;
        if ( empForm.getJobState ( ) != null ) request.setAttribute ( "jobState_" , empForm.getJobState ( ) ) ;
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		        
        return mapping.findForward( "empList" );
    }
    
	
	public ActionForward editEmpIndex ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		if ( empForm.isValidEmpId ( ) ) {
			UserEmplyVo userEmplyVo = getGroupManager ( ).loadEmpWithUser (
					empForm.getEmpId ( ) );
			PropertyUtils.copyProperties ( empForm , userEmplyVo );
			request.setAttribute ( "titleId" , userEmplyVo.getTitleId ( ) ); // TODO
			if ( userEmplyVo.getUserVo ( ) != null ) {
				PropertyUtils.copyProperties ( empForm , userEmplyVo
						.getUserVo ( ) );
			}
			request.setAttribute ( "cgrpid" , userEmplyVo.getGrpId ( ) );
		}
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		return new ActionForward( "/modules/org/empManager.jsp" );
	}

    public ActionForward editEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        EmpForm empForm = (EmpForm) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
        if ( empForm.isValidEmpId() ) {
			UserEmplyVo userEmplyVo = getGroupManager ( ).loadEmpWithUser ( empForm.getEmpId ( ) );
            PropertyUtils.copyProperties( empForm , userEmplyVo );
            request.setAttribute ( "titleId" , userEmplyVo.getTitleId ( ) ) ; // TODO
            if ( userEmplyVo.getUserVo() != null ) {
            	PropertyUtils.copyProperties( empForm, userEmplyVo.getUserVo() );
            }
            request.setAttribute ( "cgrpid" , userEmplyVo.getGrpId ( ) );
        }

        request.getSession ( ).removeAttribute (  SESSION_TITLES ) ;
        request.getSession ( ).removeAttribute ( SESSION_ROLES ) ;
		if ( empForm.isValidEmpId ( ) ) {
			//List usedRoles  = OrgFactory.getUserManager ( ).queryRolesOfUser ( getGroupManager ( ).loadUserByEmp ( empForm.getEmpId ( ) ) );
			//request.getSession ( ).setAttribute ( SESSION_ROLES , usedRoles ) ;
		}

        List allTitles = getGroupManager().queryTitlesOfGroup( empForm.getGrpId() );
        List idtypes = DictionaryCache.getInstance ( ).listBizOptions ( "idtype" , false );
        List sexs = DictionaryCache.getInstance ( ).listBizOptions ( EMP_SEX , false );
        List jobstates = DictionaryCache.getInstance ( ).listBizOptions ( EMP_JOBSTATE , false );
        List edulevels = DictionaryCache.getInstance ( ).listBizOptions ( "edulevel" , false );
        List bloodtypes = DictionaryCache.getInstance ( ).listBizOptions ( "bloodtype" , false );
		request.setAttribute ( "allTitles" , allTitles );
		request.setAttribute ( "idtypes" , idtypes );
		request.setAttribute ( "sexs" , sexs );
		request.setAttribute ( "jobstates" , jobstates );
		request.setAttribute ( "edulevels" , edulevels );
		request.setAttribute ( "bloodtypes" , bloodtypes );
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		return mapping.findForward ( "empEdit" );
   }

    public ActionForward saveEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		String cgrpid = request.getParameter ( "cgrpid" ) == null ? "" : request.getParameter ( "cgrpid" );
		SessionUserInfo currentUser = getCurrentUser ( request );
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		String oldLoginName = empForm.getOldLoginName ( ) ;
		String currentTab = empForm.getCurrentTab ( ) ; 
        UserEmplyVo userEmplyVo = new UserEmplyVo();
        PropertyUtils.copyProperties ( userEmplyVo , empForm );
		userEmplyVo.setOperUser ( currentUser.getUserId ( ) );
		
		//
		
		StringBuffer to = new StringBuffer( "orgSuccess.go?type=emp" ) ;
		
		//check 
		if ( empForm.getEmpCode ( ) != null && 
				! "".equals (  empForm.getEmpCode ( ).trim ( )  )  &&
				! empForm.getEmpCode ( ).equals ( empForm.getOldEmpCode ( ) ) ) {
			UserEmplyVo userEmplyVo__ = OrgFactory.getGroupManager ( ).loadEmpByEmpCode ( empForm.getEmpCode ( ).trim ( ) ) ; 
			if ( userEmplyVo__ != null  ) {
				Error error = new Error();
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.employee.code.already.exist" , request.getLocale ( ) ) );
				error.setErrorInfo ( userEmplyVo__.getEmpName ( ) + ":" + userEmplyVo__.getEmpCode ( ) , true ) ;
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;				
			}
		}
		
		
        //
        if ( ( empForm.getUserId ( ) != null && empForm.getUserId ( ).longValue ( ) != 0 ) || 
        	   ( GetterUtil.get ( empForm.getLoginName ( ) , null )  != null   )   ) {
            UserVo userVo = new UserVo();
            PropertyUtils.copyProperties( userVo, empForm );
            userEmplyVo.setUserVo( userVo );
        }

        //
        if (  empForm.getTitleId ( ) != null && empForm.getTitleId ( ).longValue ( ) != 0  ) {
        	TitleMsgVo title =  getGroupManager ( ).loadTitle ( empForm.getTitleId ( )  ) ;
        	userEmplyVo.setTitleMsgVo ( title ) ;
        }

        
		if ( StringUtils.isNotEmpty ( empForm.getCsvTitleIds ( ) ) ) { // sTitleIds
			String [ ] sTitleIds = StringUtils.split ( empForm.getCsvTitleIds ( ) , ',' );
			Long[] titleIds = new Long[ sTitleIds.length ]  ;
			List titleList = new java.util.ArrayList( titleIds.length ) ;
			for ( int i = 0 ; i < sTitleIds.length ; i ++ )
				titleIds[ i ] = Long.valueOf ( sTitleIds[ i ].trim ( ) ) ;
			if ( titleIds .length > 0  ) titleList = getGroupManager ( ).queryTitlesByIds( titleIds ) ;
			userEmplyVo.setTitleList ( titleList );
		}
		else {
			if ( !"title".equals ( currentTab ) && request.getSession ( ).getAttribute ( SESSION_TITLES ) != null ) {
				List titleList = ( List ) request.getSession ( ).getAttribute ( SESSION_TITLES ) ;
				userEmplyVo.setTitleList ( titleList );				
			}
		}
		
		
		if ( StringUtils.isNotEmpty ( empForm.getCsvRoleIds ( ) ) ) { // sRoleIds	
			String [ ] sRoleIds = StringUtils.split ( empForm.getCsvRoleIds ( ) , ',' );
			List roleList  = OrgFactory.getRoleManager ( ).queryRolesByIds ( sRoleIds );
			userEmplyVo.getUserVo ( ).setRoleList ( roleList );			
		}
		
        //
        GroupManager groupManager = getGroupManager();
		if ( empForm.isValidEmpId ( ) ) { //update
			if ( userEmplyVo.getUserVo ( ) != null ) {
				if ( oldLoginName != null && !oldLoginName.equals ( userEmplyVo.getUserVo ( ).getLoginName ( ) ) ) {
					if ( groupManager.countLoginName ( userEmplyVo.getUserVo ( ).getLoginName ( ) )	.longValue ( ) > 0 ) {
						Error error = new Error();
						error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.loginname.already.exist" , request.getLocale ( ) ) );
						request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
						return mapping.findForward( "glerror" ) ;
					}					
				}
			}
			if ( null != userEmplyVo.getIdType ( ) && null != userEmplyVo.getIdNo ( ) ) {
				UserEmplyVo  evo = groupManager.loadEmp ( userEmplyVo.getEmpId ( ) );
				String idtype = evo.getIdType ( ) == null ? "" : evo.getIdType ( ); 
				String idno = evo.getIdNo ( ) == null ? "" : evo.getIdNo ( );
				if (!idtype.equals ( userEmplyVo.getIdType ( )) || !idno.equals ( userEmplyVo.getIdNo ( ) ) )  {
					if (userEmplyVo.getIdType ( ) !=null && userEmplyVo.getIdNo ( )!=null) {
						if ( groupManager.countIdNOByIdType ( userEmplyVo ).longValue ( ) > 0 ) {
							Error error = new Error();
							error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.employee.idno.already.exist" , request.getLocale ( )  ) );
							request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
							return mapping.findForward( "glerror" ) ;
						}
					}
				}
			}
			userEmplyVo.setGrpId ( Long.valueOf ( cgrpid ) );
			fillUpdtUser ( request , userEmplyVo ); 
			groupManager.updateEmpAndAllRel ( userEmplyVo ,  empForm.isTuser ( ) );
			to.append ( "&empId=" ).append ( empForm.getEmpId ( ) ) ;
		}
        else {
            // TODO pre-check new
			if ( userEmplyVo.getUserVo ( ) != null ) {
				if ( oldLoginName != null && !oldLoginName.equals ( userEmplyVo.getUserVo ( ).getLoginName ( ) ) ) {
					if ( groupManager.countLoginName ( userEmplyVo.getUserVo ( ).getLoginName ( ) )	.longValue ( ) > 0 ) {
						Error error = new Error();
						error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.loginname.already.exist" ,  request.getLocale ( )  ) );
						request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
						return mapping.findForward( "glerror" ) ;
					}
				}
			}
			if (!"".equals ( userEmplyVo.getIdType ( ) ) && !"".equals ( userEmplyVo.getIdNo ( ) )) {
				if ( groupManager.countIdNOByIdType ( userEmplyVo ).longValue ( ) > 0 ) {
					Error error = new Error();
					error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.employee.idno.already.exist" , request.getLocale ( )  ) );
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;
				}
			}
			fillCrtUser ( request , userEmplyVo );
			groupManager.createEmpAndAllRel ( userEmplyVo );
			Long empId = userEmplyVo.getEmpId ( ) ;
			to.append ( "&empId=" ).append ( empId ) ;
			
        }

		if ( empForm.getUserId ( ) != null && empForm.getUserId ( ).longValue ( ) != 0  &&
        	    GetterUtil.get ( empForm.getLoginName ( ) , null )  != null      ) {
			String oln = GetterUtil.get ( request.getParameter ( "oldLoginName" ) , null ) ;
			String ln = GetterUtil.get ( userEmplyVo.getUserVo ( ).getLoginName ( ) , null ) ;
			if ( oln != null && !oln.equals ( ln ) ) {
				AcegiCacheManager.getInstansce ( ).modifyUserKeyInCache( oln , userEmplyVo.getUserVo ( ) ) ;
			}
		}
		
		request.getSession ( ).removeAttribute (  SESSION_TITLES ) ;
		request.getSession ( ).removeAttribute (  SESSION_ROLES ) ;
        //return mapping.findForward( "success" );
		return new ActionForward( to.toString ( ) , true ) ;
    }

    /**
     * TODO 选择兼职岗位 树
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
	public ActionForward loadChildTree ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		GroupManager groupManager = OrgFactory.getGroupManager ( );
		Long grpId = empForm.getGrpId ( ) ;
		String thtml = null ;
		if ( grpId != null && grpId.longValue ( ) != 0L ){
			List cgs = groupManager.getChildGroup ( grpId ) ;
	    	OrgGroupTree orgGroupTree = new OrgGroupTree( ) ; 
	    	orgGroupTree.setBaseName ( FuncMessageManager.get ( request.getLocale ( ) ).getMessage ( "group.tree.root" ) ) ;
	    	orgGroupTree.setSrc ( "empAction.go?method=loadChildTree&" ) ; 
	    	orgGroupTree.setRoot ( false ) ;
	    	orgGroupTree.setChildNodes (  cgs ) ;
	    	orgGroupTree.setTxtOnclick ( "__txtonclick( this )" ) ;
	    	thtml = groupManager.generateGroupTreeStr( orgGroupTree ) ;	
		}
    	
    	request.setAttribute ( "partyTree" , thtml ) ;
		return new ActionForward( "/modules/org/partyTree.jsp"  ) ;
	}

	
	public ActionForward selectTitles ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
		byte roleType = currentUser.getCurrentUserMaxRoleType ( ) ;
		EmpForm empForm = ( EmpForm ) form;
		GroupManager groupManager = OrgFactory.getGroupManager ( );

		List rootGroups = new ArrayList( 0 ) ;
		Map groupMap = new HashMap( ) ; 
		Map roots = new HashMap( ) ; 
		if ( roleType == Constants.ROLE_TYPE_ORG_MANAGER  ) {
			List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
					Constants.ROLE_TYPE_ORG_MANAGER ,
					currentUser.getUserId ( ) );
			if ( roles.size ( ) > 0 ) {
				StringBuffer roleIds = new StringBuffer() ;
				for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
					RoleVo role = ( RoleVo ) roles.get ( i ) ;
					roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
					if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
				}
				if ( roleIds.length ( ) > 0 ) {
					roots  = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
					groupMap.putAll ( roots ) ;
					rootGroups.addAll ( OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( roots ) ) ; 
				}
			} 			
		}
		else if ( roleType != Constants.ROLE_TYPE_ORG_MANAGER ) 
			rootGroups.add ( groupManager.loadGroup4SelectOption ( empForm.getGrpId ( ) )  ) ;
		
		
		GroupVo groupVo = null ; 
		if (  ( roleType == Constants.ROLE_TYPE_ORG_MANAGER && ( empForm
						.getGrpId ( ) == null || empForm.getGrpId ( )
						.longValue ( ) == 0L ) ) ) {
			groupVo = ( GroupVo )rootGroups.get ( 0 ) ; 
			groupVo.setFgrpId ( null ) ;
		}
		else if ( roleType != Constants.ROLE_TYPE_ORG_MANAGER ) {
			groupVo = ( GroupVo )rootGroups.get ( 0 ) ; 
		}	
		else {
			groupVo = groupManager.loadGroup4SelectOption ( empForm.getGrpId ( ) ) ;
			//check
			if (  roleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
				if ( groupMap != null && !groupMap.containsKey ( groupVo.getGrpId ( ) ) ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ;
				if ( roots.containsKey ( groupVo.getGrpId ( ) ) ) groupVo.setFgrpId ( null ) ;
			}						

		}
			
		
		
		
		
		
		
		if ( StringUtils.isNotEmpty ( empForm.getCsvTitleIds ( ) ) ) { // sTitleIds
			String [ ] sTitleIds = StringUtils.split ( empForm.getCsvTitleIds ( ) , ',' );
			if ( sTitleIds .length > 0 ) {
				Long[] titleIds = new Long[ sTitleIds.length ]  ;
				for ( int i = 0 ; i < sTitleIds.length ; i ++ )
					titleIds[ i ] = Long.valueOf ( sTitleIds[ i ].trim ( ) ) ;
				List ts = getGroupManager ( ).queryTitlesByIds( titleIds )  ; 
				java.util.Collections.reverse ( ts  ) ;
				request.getSession ( ).setAttribute ( SESSION_TITLES , ts  );											
			}
		}
		
		List allTitles = getGroupManager ( ).queryTitlesOfGroup ( empForm.getGrpId ( ) );
		List usedTitles = new ArrayList ( 0 );
		if ( empForm.isValidEmpId ( ) ) {
			usedTitles = getGroupManager ( ).queryTitlesOfEmp ( empForm.getEmpId ( ) );
		}	

		//since 1.51
		/*
		if ( roleType == Constants.ROLE_TYPE_ORG_MANAGER ) {			
			Map rootGroupsMap = new java.util.TreeMap( ) ;  
			for ( java.util.Iterator iter = rootGroups.iterator ( ) ; iter.hasNext ( ) ;   ) {
				GroupVo grp = ( GroupVo ) iter.next ( ) ;
				groupManager.downLoadsGroups ( grp , rootGroupsMap  ) ; 
				if ( rootGroupsMap.containsKey ( empForm.getGrpId ( ) ) )  break ; 
			}
			if ( !rootGroupsMap.containsKey ( empForm.getGrpId ( ) ) ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ; 
			
			boolean mark = false ; 
			for ( java.util.Iterator iter = rootGroups.iterator ( ) ; iter.hasNext ( ) ;   ) {
				GroupVo grp = ( GroupVo ) iter.next ( ) ;
				if ( grp.getGrpId ( ).longValue ( ) == groupVo.getGrpId ( )
						.longValue ( ) ) {
					mark = true ; 
					break ;
				}
			}
			if ( mark ) groupVo.setParentGroupVo ( null ) ; 
		}*/

		allTitles = groupVo.getTitleList ( );

		//
		boolean mark = false ; 
		for ( java.util.Iterator iter = rootGroups.iterator ( ) ; iter.hasNext ( ) ;  ) {
			GroupVo group__ = ( GroupVo ) iter.next ( ) ;
			if ( group__.getGrpId ( ).equals (  groupVo.getGrpId ( ) ) ) {
				iter.remove ( ) ;
				mark = true ; 
				break ; 
			}
			else mark = false ; 
		}
		if ( mark == false  ) rootGroups.clear ( ) ;  
		
		
		request.setAttribute ( "groups" , rootGroups ) ; 
		request.setAttribute ( "groupVo" , groupVo );
		request.setAttribute ( "allTitles" , allTitles );
		request.setAttribute ( "usedTitles" , usedTitles );
		request.setAttribute ( "roleType" , new Integer( roleType ) ) ;
		return mapping.findForward ( "empTitleSelect" );
	}

	
	public ActionForward selectRoles ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		//session attr
		EmpForm empForm = ( EmpForm ) form;		
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ;         
		if ( StringUtils.isNotEmpty ( empForm.getCsvRoleIds ( ) ) ) { // sRoleIds
			String [ ] sRoleIds = StringUtils.split ( empForm.getCsvRoleIds ( ) , ',' );
			List roleList = OrgFactory.getRoleManager ( ).queryRolesByIds ( sRoleIds );
			request.getSession ( ).setAttribute ( SESSION_ROLES , roleList ) ;
		}	
		

		UserManager userManager = OrgFactory.getUserManager ( );
		List usedRoles = null;
		if ( empForm.isValidEmpId ( ) ) {
			UserVo userVo  = getGroupManager ( ).loadUserByEmp ( empForm.getEmpId ( ) ) ;
			if ( empForm.getRoleName ( ) != null ) {
				userVo.setRoleName ( empForm.getRoleName ( ) ) ; 
				request.setAttribute ( "roleName" , empForm.getRoleName ( ) ) ; 
			}
			if ( empForm.getStartTime ( ) != null ) {
				userVo.setStartTime ( empForm.getStartTime ( ) ) ; 
				request.setAttribute ( "startTime" , empForm.getStartTime ( ) ) ; 
			}
			if ( empForm.getEndTime ( ) != null ) { 
				userVo.setEndTime ( empForm.getEndTime ( ) ) ; 
				request.setAttribute ( "endTime" , empForm.getEndTime ( ) ) ; 
			}
			
			EctableConverts  ec = userVo.getEconverts ( ) ; 
	        ec.setProConvert ( "crtTime" , "a.crtTime" ) ;
			EXTableUtils.initLimitPage(  userVo , request ) ;
			Long rl = userManager.countgetRolesByUser ( userVo ) ;
			userVo.setTotalRows ( rl.intValue ( ) ) ;
			EXTableUtils.setLimitRowAttributes (  userVo , request ) ;
			usedRoles = userManager.queryRolesOfUser ( userVo , CONST.PAGE );
		}
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		empForm.setUsedRoles ( usedRoles );
		return mapping.findForward ( "empRoleSelect" );
	}

    private GroupManager getGroupManager() throws CheckException {
        return OrgFactory.getGroupManager ( ) ;
    }
    
    private UserManager getUserManager() throws CheckException {
        return OrgFactory.getUserManager();
    }
    
    //瀵嗙爜淇敼
    public ActionForward passIndex(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward ( "passindex" );
	}
    
    public ActionForward passManager(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward ( "passmanager" );
	}
    
    public ActionForward updatePass(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String flag = request.getParameter ( "flag" );
		request.setAttribute ( "flag" , flag );
		return mapping.findForward ( "updatePass" );
	}
    
    ///@author  zhouxiaoyun
    public ActionForward savePass(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    		throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		String flag = request.getParameter ( "flag" );
		String password = empForm.getPassword ( ).toString ( ) == null ? "" : empForm.getPassword ( ).toString ( );
		SessionUserInfo currentUser = getCurrentUser ( request );
		// 
		Long userid = currentUser.getUserInfo ( ).getUserId ( );
		boolean workflag = currentUser.getUserInfo ( ).getWorkFlg ( )
				.booleanValue ( );
		String loginname = currentUser.getUserInfo ( ).getLoginName ( );
		UserVo uservo = new UserVo ( );
		uservo.setWorkFlg ( new Boolean ( workflag ) );
		uservo.setLoginName ( loginname );
		uservo.setUserId ( userid );
		uservo.setPassword ( password );
		uservo.setUpdtUser ( userid );
		//
		uservo.setLastModPassTime ( new Date( ) ) ; 
		if ( "person".equals ( flag ) ) {
			getUserManager ( ).updatePassword ( uservo );
			if ( "checkPass".equals ( request.getParameter ( "m" ) ) ) {
				currentUser.setCheckPassState ( true ) ; 
				return mapping.findForward ( "checkPassSuccess" ) ;
			}
				
		} else if ( "all".equals ( flag ) ) { // 
			UserVo uvo = new UserVo ( );
			uvo.setPassword ( password );
			uvo.setUpdtUser ( userid );
			uvo.setLastModPassTime ( new Date( ) ) ; 
			List userlist = getUserManager ( ).getSearchUsers ( uvo );
			getUserManager ( ).updateAllPassword ( uvo , userlist );
		} else { // 
			Long [ ] deleteIds = empForm.getDeleteId ( );
			UserVo vo = new UserVo ( );
			if ( deleteIds != null ) {
				String [ ] userIds = new String [ deleteIds.length ];
				for ( int i = 0 ; i < deleteIds.length ; i ++ ) {
					userIds [ i ] = deleteIds [ i ].toString ( );
				}
				vo.setUpdtUser ( userid );
				vo.setUserIds ( userIds );
				vo.setPassword ( password );
				vo.setLastModPassTime ( new Date( ) ) ; 
				List userlist = getUserManager ( ).getSearchUsers ( vo );
				getUserManager ( ).updateAllPassword ( vo , userlist );
			} else {
				String msg = "1";
				request.setAttribute ( "msg" , msg );
				return new ActionForward ( "/empAction.go?method=listAllEmp" );
			}
		}
		if ( "search".equals ( flag ) ) {
			String msg = "2";
			request.setAttribute ( "msg" , msg );
			return new ActionForward ( "/empAction.go?method=listAllEmp" );
		}
		return mapping.findForward ( "success" );
	}
    
	
	
	public ActionForward removeEmp ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
		EmpForm empForm = ( EmpForm ) form;
		Long grpId = empForm.getGrpId ( );
		Long [ ] deleteIds = empForm.getDeleteId ( );
		if ( deleteIds != null ) {
			for ( int i = 0 ; i < deleteIds.length ; i ++ ) {
				Long deleteId = deleteIds [ i ];
				getGroupManager ( ).removeEmpWidthRels ( deleteId , currentUser.getUserId ( ));
				
			}
		}
		return new ActionForward (
				"empAction.go?method=listEmp&grpId=" + grpId , true );
	}
	
	public ActionForward listAllEmp ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		UserVo userVo = new UserVo ( );
		userVo.setEmpNameSearch ( empForm.getEmpName ( ) );
		PropertyUtils.copyProperties ( userVo , empForm ) ;
		UserEmplyVo userEmplyVo = new UserEmplyVo();
		EXTableUtils.initLimitPage(  userVo , request ) ;
		Long lr = getUserManager ( ).countEmpAllList ( userVo );
		userVo.setTotalRows ( lr.intValue ( ) ) ; 
		EXTableUtils.setLimitRowAttributes(  userVo , request ) ;
		
		List emplist = getUserManager ( ).getEmpAllList ( userVo );
		userEmplyVo.setEmpList ( emplist );
		if ( empForm.getEmpCode ( ) != null ) request.setAttribute ( "empCode" , empForm.getEmpCode ( ) ) ;
		if ( empForm.getEmpName ( ) != null ) request.setAttribute ( "empName" , empForm.getEmpName ( ) ) ;
        if ( empForm.getLoginName ( ) != null ) request.setAttribute ( "loginName" , empForm.getLoginName ( ) ) ;
		request.setAttribute ( "userEmplyVo" , userEmplyVo );
		return mapping.findForward ( "searchemplist" );
	}
	
	public ActionForward selectGroup ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		StringBuffer sb = new StringBuffer();
		GroupVo groupVo = new GroupVo();
		UserEmplyVo userEmplyVo = new UserEmplyVo();
		List grouplist = getGroupManager ( ).getGroupTrees(groupVo);
		for ( int i = 0 ; i < grouplist.size ( ) ; i ++ ) {
			groupVo = ( GroupVo ) grouplist.get ( i );
			sb.append ( "d.add(" + groupVo.getGrpId ( ) + ","
							+ groupVo.getFgrpId ( ) + ",'" + groupVo.getChnName ( )
							+ "');" );
		}
		String empids  = request.getParameter ( "empids" );
		String[] ids;
		ids = empids.split(",");
		userEmplyVo.setEmpids(ids);
		List emplist = getGroupManager().getEmpJobstate(userEmplyVo);
		for (int j = 0;j<emplist.size();j++) {
			userEmplyVo = (UserEmplyVo)emplist.get(j);
			if (userEmplyVo.getJobState().equals(Constants.JOBSTATE_IN)) {
				Error error = new Error();
				error.setErrorTitle ( OrgMessageManager.get().getMessage("org.emply.jobstate") );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;
			}
		}
		
		String msg = request.getParameter ( "msg" );
		request.setAttribute ( "msg" , msg );
		request.setAttribute("empids", empids);
		request.setAttribute ( "grouptree" , sb.toString ( ) );
		return mapping.findForward ( "empGroupSelect" );
	}
	
	public ActionForward moveEmp ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		UserEmplyVo userEmplyVo = new UserEmplyVo ( );
		String empIds = request.getParameter ( "empids" );
		String grpId = request.getParameter ( "grpId" );
		String [ ] ids;
		ids = empIds.split ( "," );
		userEmplyVo.setGrpId ( Long.valueOf ( grpId ) );
		for ( int i = 0 ; i < ids.length ; i ++ ) {
			userEmplyVo.setEmpId ( Long.valueOf ( ids [ i ] ) );
			getGroupManager ( ).updateEmpOfGroup ( userEmplyVo );
		}
		return new ActionForward ( "/empAction.go?method=selectGroup&msg=1" , true );
    }

	
	public ActionForward toAuthIndex ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 		
		byte roleType = currentUser.getUserRoleType ( ) ; 
		List soptions = OrgFactory.getRoleManager ( ).getRoleTypes ( roleType , false )  ;
		request.setAttribute ( "options" , soptions ) ;	
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;								
		return mapping.findForward ( "authIndex" );
	}

	
	public  ActionForward loadRoleAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );		
		Long userId = OrgFactory.getGroupManager ( ).loadUserByEmp ( empForm.getEmpId ( ) ) .getUserId ( );
		//load all roles
		RoleManager roleManager = OrgFactory.getRoleManager ( ) ;
		List roles = roleManager.getRoles (  empForm.getRoleType ( ) ) ; 
		request.setAttribute ( "roles" , roles ) ;
		
		//load select roles
		UserEmplyVo ueVo = new UserEmplyVo() ; 
		PropertyUtils.copyProperties ( ueVo , empForm ) ;
		
		List userOfRoles = OrgFactory.getUserManager ( ).getRolesByUser ( empForm.getRoleType ( ) , userId ) ;
		request.setAttribute ( "userOfRoles" , userOfRoles );	
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;										
		return mapping.findForward ( "userAuth" );
	}
	
	
	public  ActionForward doRoleAuth( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte cuRoleType =  currentUser.getCurrentUserMaxRoleType ( );
        if ( cuRoleType > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		Long empId = empForm.getEmpId ( ) ; 
		byte roleType = empForm.getRoleType ( ) ;
		if ( roleType <= cuRoleType  ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   

		UserVo user = OrgFactory.getGroupManager ( ).loadUserByEmp ( empId ) ;	
		user.setOperUser ( currentUser.getUserId ( ) );
		OrgFactory.getUserManager ( ).saveUserRoleRel ( user , roleType , empForm.getPrincipalIds ( ) ) ;
		
		StringBuffer to = new StringBuffer() ; 
		to.append ( "empAction.go?method=loadRoleAuths&empId=" )
          .append ( empId ).append ( "&roleType=" ).append ( roleType ) ; 
		return new ActionForward( to.toString ( ) ,  true  ) ;
	}
	
	public  ActionForward deleteRoleAuth( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		UserVo user = OrgFactory.getGroupManager ( ).loadUserByEmp ( empForm.getEmpId ( ) ) ;	
		Long[] deleteIds = empForm.getDeleteId ( ) ; 
		OrgFactory.getUserManager ( ).deleteUserRoleRel( user , deleteIds , currentUser.getUserId ( ) ) ; 
		StringBuffer to = new StringBuffer() ; 
		to.append ( "empAction.go?method=selectRoles" );
		to.append ( "&grpId=" ).append ( empForm.getGrpId ( ) );
		to.append ( "&empId=" ).append ( empForm.getEmpId ( ) ) ; 
		
		String ecp = request.getParameter ( "ec_p_" ) ;
		if ( ecp != null && !"".equals ( ecp ) ) to.append ( "&ec_p_=" ).append ( ecp ) ;				
		return new ActionForward( to.toString ( ) ,  true  ) ;		
	}
	

	public  ActionForward empIdPhones( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   

        Long empId = empForm.getEmpId ( ) ; 
        if ( NumberUtils.isEmptyOrZero ( empId ) ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
        
        UserEmplyVo userEmplyVo = getGroupManager ( ).loadEmp ( empForm.getEmpId ( ) );
        request.setAttribute ( "emp" , userEmplyVo ) ;
        
        return new ActionForward( "/modules/org/empIdPhones.jsp" ) ;
	}
	
	
	
	public  ActionForward editEmpIdPhone( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		
		//
		EmpForm empForm = ( EmpForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   

        Long empId = empForm.getEmpId ( ) ; 
        if ( NumberUtils.isEmptyOrZero ( empId ) ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
	
        UserEmplyVo userEmplyVo = getGroupManager ( ).loadEmpWithUser (  empForm.getEmpId ( ) );
       
        
        if( Constants.ORG_EMP_PHONE_Z.equals ( empForm.getPhoneFlg ( ) ) ) {
        	saveAndUpdateEmpPhone( userEmplyVo ,  empForm.getIdPhone1ff ( ) , getGroupManager ( ) , request , "idPhone1" ) ;
        }
        if( Constants.ORG_EMP_PHONE_F.equals ( empForm.getPhoneFlg ( ) ) ) {
        	saveAndUpdateEmpPhone( userEmplyVo ,  empForm.getIdPhone2ff ( ) , getGroupManager ( ) , request , "idPhone2" ) ;
        }
        
        userEmplyVo = getGroupManager ( ).loadEmpWithUser (  empForm.getEmpId ( ) );
        request.setAttribute ( "emp" , userEmplyVo ) ;
        //
        return new ActionForward( "empAction.go?method=empIdPhones&empId=" + empId  , true ) ;
	}
		
	
	private Long saveAndUpdateEmpPhone( UserEmplyVo user , FormFile formFile  , GroupManager groupManager , HttpServletRequest request , String phonetype ) throws Exception {
		Long empId = user.getEmpId ( ) ; 
		String uploadFn = formFile.getFileName ( ); 
		if ( ! StringUtils.isEmpty ( uploadFn )
				&& ! StringUtils.isBlank ( uploadFn ) ) {
			FileUploadUtil upload = new FileUploadUtil ( );
			ThreadSynchronizer.threadEnter ( );
			try {
				upload.setRestrictfs ( 102400 * 8 );
				String fn = upload.uploadv2 ( formFile , request ,
						Constants.ORG_EMP_POHONE_PATH , UUID.randomUUID ( )
								.toString ( ) );
				fn = Constants.ORG_EMP_POHONE_PATH + fn;
				PropertyUtils.setProperty ( user , phonetype , fn );
			} finally {
				ThreadSynchronizer.threadExit ( );
			}
		}
		
		if ( ! NumberUtils.isEmptyOrZero ( empId ) ) { // update
			UserEmplyVo vo = groupManager.loadEmpWithUser ( empId ); 
			String cardImg = ( PropertyUtils.getProperty ( vo , phonetype ) != null ? PropertyUtils
					.getProperty ( vo , phonetype ).toString ( )
					: "" ); 
			if ( StringUtils.isEmpty ( uploadFn )
					|| StringUtils.isBlank ( uploadFn ) )
				PropertyUtils.setProperty ( user , phonetype , cardImg );
			else {
				FileUploadUtil.removeRealPathFile ( cardImg , request );
			}
			groupManager.updateEmp ( user );
		}
		//upload

		return empId ; 
	}	
	
}
